package com.xishu.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xishu.client.HttpClientUtil;
import com.xishu.config.Config;
import com.xishu.exception.ResponseStatusException;
import com.xishu.response.ResponseStatus;
import com.xishu.response.VerifyUtil;
import com.xishu.util.AES;
import com.xishu.util.Tools;

import java.util.HashMap;
import java.util.Map;

public class RecaptchaService implements Tools {
    private static RecaptchaService instance = new RecaptchaService();

    private RecaptchaService() {
    }

    public static RecaptchaService getInstance() {
        return instance;
    }

    public void check(String token, double lowScore) throws ResponseStatusException {
        Map<String, String> paramMap = new HashMap<>();
        String recaptchaKey = AES.decrypt(Config.getInstance().recaptchaKey());
        paramMap.put("secret", recaptchaKey);
        paramMap.put("response", token);

        String responseStr = HttpClientUtil.post("https://www.google.com/recaptcha/api/siteverify", new HashMap<>(), paramMap);
        JSONObject json = JSON.parseObject(responseStr);
        Boolean success = json.getBoolean("success");

        VerifyUtil.verify(() -> getBoolean(success), ResponseStatus.SYSTEM_BUSY);
        Double score = json.getDouble("score");
        VerifyUtil.verify(() -> getDouble(score) >= lowScore, ResponseStatus.SYSTEM_BUSY);
    }
}
